package cn.antho.org.service.impl;

import cn.antho.basic.config.BussinessException;
import cn.antho.basic.util.BaiduAuditUtils;
import cn.antho.basic.util.EmailUtil;
import cn.antho.org.domain.Employee;
import cn.antho.org.domain.Shop;
import cn.antho.org.domain.ShopAuditLog;
import cn.antho.org.enu.ShopStateEum;
import cn.antho.org.mapper.EmployeeMapper;
import cn.antho.org.mapper.ShopAuditLogMapper;
import cn.antho.org.mapper.ShopMapper;
import cn.antho.org.service.IEmployeeService;
import cn.antho.org.service.IShopService;
import cn.antho.basic.service.impl.BaseServiceImpl;
import cn.antho.org.vo.ShopEchartsVo;
import cn.antho.user.service.ILogininfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author antho
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender sender;

    @Autowired
    private ILogininfoService logininfoService;

    /**
     * 店铺入驻流程
     * @param shop
     */
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        Employee employee = this.verify(shop, admin);
        // 存入数据，添加shop表
        shopMapper.add(shop);
        if (null == employee) {
            // 添加emp
            employee = admin;
            employeeService.add(employee);
            // 修改emp的shopId
            employee.setShopId(shop.getId());
            employeeService.update(employee);
            // 修改shop表的adminId
            Shop updateShop = new Shop();
            updateShop.setId(shop.getId());
            updateShop.setAdminId(employee.getId());
            shopMapper.update(updateShop);
        }
    }

    @Override
    public void auditPass(ShopAuditLog shopAuditLog) {
        // 判断参数
        if (StringUtils.isBlank(shopAuditLog.getNote())) {
            throw new BussinessException("警告！备注不能为空！");
        }
        // 修改店铺的状态为 待激活（审核通过）
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        // 添加店铺日志
        // 登录注册还没有做 审核人id写死
        shopAuditLog.setAuditId(420L);
        shopAuditLogMapper.add(shopAuditLog);
        /*// 发送邮件
        // 创建复杂邮件对象
        MimeMessage mimeMessage = sender.createMimeMessage();
        // 发送复杂的邮件
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("575786294@qq.com");
            helper.setSubject("宠物之家审核结果通知");
            // 设置文本内容
            helper.setText("<h2>恭喜您审核通过，点击下方链接激活店铺<h2>" + "http://localhost:8080/shop/active/" + shopAuditLog.getShopId(), true);
            // 设置收件人
            helper.setTo("575786294@qq.com");
        } catch (Exception e) {
            throw new BussinessException("邮件发送错误！");
        }
        // 发送邮件
        sender.send(mimeMessage);*/
        String text = "<h2>恭喜您审核通过，点击下方链接激活店铺<h2>" + "http://localhost:8080/shop/active/" + shopAuditLog.getShopId();
        EmailUtil.sendEmail("宠物之家店铺入驻审核结果",text,"575786294@qq.com");
    }

    /**
     * 店铺激活
     */
    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    /**
     * Echarts
     * @return
     */
    @Override
    public Map<String, Object> echarts() {
        Map<String,Object> result = new HashMap<>();
        List<ShopEchartsVo> vo= shopMapper.echarts();
        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
//        List<Integer> xT = new ArrayList<>();
//        for (ShopEchartsVo echartsVo : vo) {
//            xT.add(echartsVo.getState());
//        }
        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());
        List<String> realX = new ArrayList<>();
        for (Integer xTemp : x) {
            String stateName = ShopStateEum.getNameByCode(xTemp);
            realX.add(stateName);
        }
        result.put("x",realX);
        result.put("y",y);
        return result;
    }

    /**
     * 店铺驳回
     */
    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
        // 判断备注是否为空
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空！");
        }
        /*
         * 修改店铺状态
         */
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        /*
         * 添加店铺日志
         */
        shopAuditLog.setAuditId(1025L);
        shopAuditLogMapper.add(shopAuditLog);
        /*
         * 发送邮件通知用户
         */
//        // 1.创建复杂邮件对象
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        // 2.发送复杂邮件的工具类
//        MimeMessageHelper helper = null;
//        try {
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("1605503320@qq.com");
//            helper.setSubject("宠物之家店铺入驻审核结果");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>您店铺审核驳回，点击下方链接重新填写店铺信息</h1>"+
//                    "http://localhost:8081/#/registerAgain?shopId="+shopAuditLog.getShopId(),true);
//            // 5.设置收件人
//            helper.setTo("1605503320@qq.com");
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            throw new BussinessException("发送邮件失败！");
//        }
//        // 6.发送邮件
//        javaMailSender.send(mimeMessage);
        String text = "<h1>您店入驻被驳回，请点击下方链接重新填写店铺信息</h1>"+
                "http://localhost:8081/#/registerAgain?shopId="+shopAuditLog.getShopId();
        EmailUtil.sendEmail("宠物之家店铺入驻审核结果",text,"1605503320@qq.com");

    }

    @Override
    public void addAll(List<Shop> shops) {
        shopMapper.addAll(shops);
    }

    // 校验参数
    private Employee verify(Shop shop, Employee admin) {
        // 校验参数todo
        if (StringUtils.isBlank(shop.getName())) {
            throw new BussinessException("警告！店铺名称不可为空！");
        }
        // 校验两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BussinessException("警告！两次密码不一致！");
        }
        // Ai 验证
        if (!BaiduAuditUtils.TextCensor(shop.getName())) {
            throw new BussinessException("警告！请输入合法信息！");
        }
        // 校验店铺名称是否存在
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if (null != tmpShop) {
            throw new BussinessException("警告！店铺已经存在！");
        }
        // 校验当前管理员是否管理了其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (null != employee && null != employee.getShopId()) {
            Shop shopById = shopMapper.findById(employee.getId());
            if (shopById.getAdminId().equals(employee.getId())) {
                throw new BussinessException("当前管理员已经管理了其他店铺！");
            }
        }
        return employee;
    }
}
